<template>
  <div>
    <a-tree-select
      v-if="type === 'treeSelect'"
      v-model="selectValue"
      style="width: 183px"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :tree-data="selectData"
      :placeholder="'请选择' + searchItem.filedName"
      tree-default-expand-all
      :replaceFields="replaceFields"
      @change="(e) => change(e)"
    >
    </a-tree-select>
    <a-select
      v-else
      :style="{ width: searchItem.filedName == '项目名称' ? '350px' : '183px' }"
      :mode="mode"
      :placeholder="'请选择' + searchItem.filedName"
      @change="(e) => change(e)"
      v-model="selectValue"
    >
      <a-select-option
        v-for="(item, key) in selectData"
        :key="key"
        :value="getValue(item)"
        :label="saveValue ? item[saveValue] : item.dicItemCode"
      >
        <span
          style="display: inline-block;width: 100%"
          :title="item.dicItemName || item.label"
        >
          {{ showValue ? item[showValue] : item.label || item.dicItemName }}
        </span>
      </a-select-option>
    </a-select>
  </div>
</template>

<script>
export default {
  props: [
    "searchItem",
    "formJsonData",
    "value",
    "mode",
    "saveCode",
    "showCode",
    "type",
  ],
  inject: {
    sameValue: {
      default: undefined,
    },
  }, //静态值时保存值与显示值一致
  data() {
    return {
      selectData: [],
      selectValue: "",
      dataType: "",
      dynamic: true,
      replaceFields: {
        children: "children",
        title: "text",
        key: "value",
        value: "value",
      },
      saveValue: "",
      showValue: "",
    };
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler: function(e) {
        this.selectValue = this.value;
      },
    },
    dataType: {
      handler: function(e) {
        if (e == "dynamic") {
          this.dynamic = true;
        } else {
          this.dynamic = false;
        }
      },
    },
    saveCode: {
      deep: true,
      immediate: true,
      handler: function(e) {
        this.saveValue = e;
      },
    },
    showCode: {
      deep: true,
      immediate: true,
      handler: function(e) {
        this.showValue = e;
      },
    },
  },
  mounted() {
    this.getFormDesignByFiled();
  },
  methods: {
    // 返回是否需要保存值一致
    getValue(item) {
      // 动态值
      if (this.saveValue && this.dynamic) {
        return item[this.saveValue];
      } else if (this.sameValue && !this.dynamic) {
        //切换值属性会自动切换dynamic 可以不做  （需要值与显示一致）
        return item.dicItemName;
      } else {
        //不需要值与显示一致
        return item.dicItemCode;
      }
    },
    // JSON格式数据转JS格式
    parseData(data) {
      try {
        // 尝试 JSON.parse 两次
        const parsedData = JSON.parse(JSON.parse(data));
        return parsedData;
      } catch (error) {
        try {
          // 如果报错，再尝试 JSON.parse 一次
          const parsedData = JSON.parse(data);
          return parsedData;
        } catch (error) {
          // 如果再次报错，返回原始数据
          return data;
        }
      }
    },
    getFormDesignByFiled(e) {
      let list = JSON.parse(this.formJsonData).list;
      this.flatten(list).forEach((item) => {
        if (this.searchItem.filed === item.model) {
          this.dataType = item.options.dataType;
          if (item.options.dataType === "static") {
            this.selectData = item.options.options || [];
          } else if (item.options.dataType === "dynamic") {
            // let params = getObjectByString(item.options.parameter, ",", ":");
            this.$axios(
              item.options.method,
              item.options.url,
              item.options.parameter
            ).then((res) => {
              this.selectData = this.parseData(res.data).data;
              if (item.options.saveCode) {
                this.saveValue = item.options.saveCode;
              }
              if (item.options.showCode) {
                this.showValue = item.options.showCode;
              }
            });
          } else {
            this.$post("/system/dicSet/getDicItemByCode", {
              code: item.options.dictCode,
            }).then((res) => {
              this.selectData = res.data || [];
            });
          }
        }
      });
    },
    flatten(data) {
      let result = [];
      if (!Array.isArray(data)) {
        if (data.columns || data.list || data.trs || data.tds) {
          result = result.concat(
            this.flatten(data.columns || data.list || data.trs || data.tds)
          );
        } else {
          result.push(data);
        }
      } else {
        for (let i = 0; i < data.length; i++) {
          result = result.concat(this.flatten(data[i]));
        }
      }
      return result;
    },
    change(e) {
      this.$emit("input", e);
    },
  },
};
</script>

<style></style>
